import { makeObservable, observable, action, autorun, runInAction } from "mobx";
import apiService from "../services/ApiServices";
import { Dimensions } from "react-native";

const screenWidth = Dimensions.get("window").width;

class PipeStore {
  pipeList: any[] = [];
  itemHeight: number = 0;
  isRefreshing: boolean = false;
  isLoadingMore: boolean = false;
  hasMore: boolean = true;
  tabId: string = "";
  routeKey: string = "";
  page: number = 1;

  constructor() {
    makeObservable(this, {
      pipeList: observable,
      isRefreshing: observable,
      isLoadingMore: observable,
      hasMore: observable,
      loadData: action,
      fetchData: action,
      loadMoreData: action,
      onRefresh: action,
      onSelectedItem: action,
    });

    const width = (screenWidth - 24.0) * 0.5;
    const height = 70 + (width * 16) / 11;
    this.itemHeight = height;
  }

  fetchData = async (isRefresh: boolean) => {
    try {
      if (isRefresh) {
        this.page = 1;
      }

      const result = await apiService.getTagPipeList(this.tabId, this.page);

      this.page += 1;

      runInAction(() => {
        if (isRefresh) {
          this.pipeList = result?.data || [];
        } else {
          this.pipeList = [...this.pipeList, ...(result?.data || [])];
        }
        if (result?.data?.length === 0) {
          this.hasMore = false;
        }
      });
    } catch (error) {
      console.error("获取列表数据失败:", error);
    } finally {
      runInAction(() => {
        if (isRefresh) {
          this.isRefreshing = false;
        } else {
          this.isLoadingMore = false;
        }
      });
    }
  };

  loadData = async () => {
    this.fetchData(true);
  };

  loadMoreData = async () => {
    if (this.isLoadingMore || !this.hasMore) return;
    this.isLoadingMore = true;
    await this.fetchData(false);
  };

  onRefresh = async () => {
    this.isRefreshing = true;
    await this.fetchData(true);
  };
  onSelectedItem = (id: string) => {
    this.tabId = id === "all" ? this.routeKey : id;
    console.log(this.tabId);
    this.fetchData(true);
  };
}

export default PipeStore;
